package com.leyou.item.web;

import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * specification 规格参数
 * @author 虎哥
 */
@RestController
@RequestMapping("spec")
public class SpecController {

    private final SpecGroupService groupService;

    private final SpecParamService paramService;

    public SpecController(SpecGroupService groupService, SpecParamService paramService) {
        this.groupService = groupService;
        this.paramService = paramService;
    }

    /**
     * 根据分类id查询规格组
     * @param categoryId 分类id
     * @return 规格组集合
     */
    @GetMapping("/groups/of/category")
    public ResponseEntity<List<SpecGroupDTO>> querySpecGroupByCategory(@RequestParam("id") Long categoryId){
        // select * from tb_spec_group where category_id = #{}
        List<SpecGroup> list = groupService.query().eq("category_id", categoryId).list();
        List<SpecGroupDTO> dtoList = SpecGroupDTO.convertEntityList(list);
        return ResponseEntity.ok(dtoList);
    }

    /**
     * 根据某个条件查询规格参数集合
     * @param categoryId 分类id
     * @param groupId 规格组id
     * @param searching 是否搜索
     * @return 参数集合
     */
    @GetMapping("/params")
    public ResponseEntity<List<SpecParamDTO>> querySpecParams(
            @RequestParam(value = "categoryId", required = false) Long categoryId,
            @RequestParam(value = "groupId",required = false) Long groupId,
            @RequestParam(value = "searching",required = false) Boolean searching
    ){
        List<SpecParamDTO> params = paramService.querySpecParams(categoryId, groupId, searching);
        return ResponseEntity.ok(params);
    }

    /**
     * 新增规格祖
     * @param groupDTO 规格组
     * @return 无
     */
    @PostMapping("/group")
    public ResponseEntity<Void> saveSpecGroup(@RequestBody SpecGroupDTO groupDTO){
        groupService.save(groupDTO.toEntity(SpecGroup.class));
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 根据分类id查询规格组及组内的参数
     * @param id 分类id
     * @return 组的集合，及组内参数集合
     */
    @GetMapping("list")
    public ResponseEntity<List<SpecGroupDTO>> querySpecList(@RequestParam("id") Long id){
        List<SpecGroupDTO> list = groupService.querySpecList(id);
        return ResponseEntity.ok(list);
    }
}
